import {
    checkPermission,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    getPlayerData,
    storagePlayerData
} from "../function/function.js";

export class BuyBackSelf extends plugin {
    constructor() {
        super({
            name: '[Sm]买回自己',
            dsc: '以双倍身价买回自己，身价提升20%',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]赎身$/, fnc: 'buyBackSelf' }
            ]
        })
    }

    async buyBackSelf(e) {
        try {
            // 基础检查
            if (!e.isGroup) return e.reply(['该功能只能在群内使用']);

            const config = getConfig();
            const userId = e.user_id;
            const groupId = e.group_id;

            // 确保群组和玩家数据存在
            await ensureGroupAndPlayerExist(groupId, userId);

            // 获取玩家数据
            const userData = await getPlayerData(groupId, userId);
            const { currency, value, master, buyBackTimes = 0, lastBuyBackTime = 0 } = userData;

            // 检查是否需要赎身
            if (!master) return e.reply(['你还没有主人，不需要赎身']);

            // 计算赎身价格和检查资金
            const buyBackPrice = formatCurrency(value * 2);
            if (currency < buyBackPrice) {
                return e.reply([
                    segment.at(userId),
                    `你买不起自己！需要${buyBackPrice}金币`
                ]);
            }

            // 检查赎身限制
            const currentTime = Math.floor(Date.now() / 1000);
            const { cooldown, maxTimes, taxRate } = config.buyBack;

            // 新增周数判断逻辑
            const lastBuyBackDate = new Date(lastBuyBackTime * 1000);
            const currentDate = new Date();
            const lastWeek = this.getWeekNumber(lastBuyBackDate);
            const currentWeek = this.getWeekNumber(currentDate);
            
            // 如果周数不同且超过一周，重置赎身次数
            if (currentWeek !== lastWeek && currentTime - lastBuyBackTime > 604800) {
                userData.buyBackTimes = 0;
                await storagePlayerData(groupId, userId, userData);
            }

            // 修改后的次数检查
            if (userData.buyBackTimes >= maxTimes) {
                return e.reply(['本周赎身次数已达上限，请下周再试']);
            }

            const cooldownRemaining = cooldown - (currentTime - lastBuyBackTime);
            if (!checkPermission(e) && cooldownRemaining > 0) {
                const hours = Math.floor(cooldownRemaining / 3600);
                const minutes = Math.floor((cooldownRemaining % 3600) / 60);
                return e.reply([`赎身冷却中，剩余时间：${hours}小时${minutes}分钟`]);
            }

            // 获取前主人数据
            const formerOwnerData = await getPlayerData(groupId, master);
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(groupId).getMemberMap()]);

            // 更新玩家数据
            const updatedUserData = {
                ...userData,
                currency: formatCurrency(currency - buyBackPrice),
                value: formatCurrency(value * 1.2),
                master: '',
                lastBuyBackTime: currentTime,
                buyBackTimes: userData.buyBackTimes + 1
            };

            // 计算并扣除税收
            const taxAmount = formatCurrency(updatedUserData.currency * taxRate);
            updatedUserData.currency = formatCurrency(updatedUserData.currency - taxAmount);

            // 更新前主人数据
            const updatedFormerOwnerData = {
                ...formerOwnerData,
                currency: formatCurrency(formerOwnerData.currency + buyBackPrice),
                slave: formerOwnerData.slave.filter(id => id !== userId)
            };

            // 保存数据
            await storagePlayerData(groupId, userId, updatedUserData);
            await storagePlayerData(groupId, master, updatedFormerOwnerData);

            // 发送结果消息
            await e.reply([`你支付了${taxAmount}金币的税收`]);
            return e.reply([
                `成功以${buyBackPrice}金币买回了自己！\n` +
                `现在你的身价是${updatedUserData.value}金币\n` +
                `${memberInfoList[master].nickname}获得了${buyBackPrice}金币，` +
                `现在拥有${updatedFormerOwnerData.currency}金币\n` +
                `你现在拥有${updatedUserData.currency}金币`
            ]);

        } catch (error) {
            logger.error('[赎身]处理请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试']);
        }
    }

    // 周数计算函数
    getWeekNumber(d) {
        d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
        d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
        const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
        return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
    }
}
